<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false">
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleAddSubmit" :form="form">
        <a-form-item
          label="调整金额"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-input-number
            style="width: 100%"
            max="0"
            v-decorator="['insAmount', { rules: [{ required: true, message: '请输入' }] }]"
          />
        </a-form-item>
        <a-form-item
          label="串码"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-textarea
            rows="8"
            placeholder="可添加多个,每行一个串码，错误的串码会被过滤掉"
            v-decorator="['phoneCodeList', { rules: [{ required: true, message: '请输入' }] }]"
          />
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">添加</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" title="保价商品清单">
      <a-table size="default" rowKey="key" :columns="columns" :data-source="loadData" :paginantion="false">
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#D15B47" @click="handleDel(record)">删除</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleSubmit" :form="submitform">
        <a-form-item
          label="供应商"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-select v-decorator="['supplyId',{ rules: [{ required: true, message: '请选择' }] }]" placeholder="请选择" default-value="0">
            <a-select-option :value="i.id" v-for="i in supplyoption" :key="i.id">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="保价日期"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-date-picker v-decorator="['orderDate', { initialValue:this.toDays, rules: [{ required: true, message: '请选择' }]}]" style="width: 100%" valueFormat="YYYY-MM-DD"/>
        </a-form-item>
        <a-form-item
          label="状态"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-select v-decorator="['accountType',{ rules: [{ required: true, message: '请选择' }] }]" placeholder="请选择" @select="select">
            <a-select-option value="0">待上账</a-select-option>
            <a-select-option value="1">已上账</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="预计上账"
          v-if="accountType == 0"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-date-picker v-decorator="['accountEntry', { initialValue:this.toDays, rules: [{ required: true, message: '请选择' }]}]" style="width: 100%" valueFormat="YYYY-MM-DD"/>
        </a-form-item>
        <a-form-item
          label="备注"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-input v-decorator="['memo']" placeholder="请输入备注" />
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">提交保价</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { addInsuredUsingPOST } from '@/api/api/caigouguanli.ts'
import { getPageBySingleCodeUsingGET } from '@/api/api/kucunguanli.ts'
import { getSuppliesListUsingPOST } from '@/api/api/jingxiaoshangyunyingshangguanli.ts'
import moment from 'moment'
export default {
  name: 'ProtectPrice',
  data() {
    return {
      toDays: moment().format('YYYY-MM-DD'),
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      optionParam: {
        pageNo: 1,
        pageSize: 999,
        queryCondition: '',
        status: '',
      },
      accountType:'',
      form: this.$form.createForm(this),
      submitform: this.$form.createForm(this),
      columns: [
        {
          title: '商品',
          dataIndex: 'goodName',
        },
        {
          title: '供应商',
          dataIndex: 'supplyName',
        },
        {
          title: '原成本(元)',
          dataIndex: 'commCost',
        },
        {
          title: '调整金额(元)',
          dataIndex: 'insAmount',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '220px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      supplyoption: []
    }
  },
  mounted() {
    this.getSupOption()
  },
  methods: {
    select(e){
      this.accountType = e
    },
    handleDel(record) {
      const that = this
      that.$confirm({
        title: '删除',
        content: '你确定要删除这个商品吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.loadData.splice(
            that.loadData.findIndex((item) => item.id === record.id),
            1
          )
          // this.loadData = this.loadData
        },
      })
    },
    // handler
    getSupOption() {
      getSuppliesListUsingPOST({...this.optionParam, types: '1'})
        .then((res) => {
          this.supplyoption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    removeTrim(array) {
      for (let i = 0; i < array.length; i++) {
        if (array[i] == '') {
          array.splice(i, 1)
          i = i - 1
        }
      }
      return array
    },
    handleAddSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          if(values.insAmount >= 0){
            this.$message.warn('金额不能大于等于0')
            return false
          }
          getPageBySingleCodeUsingGET({ phoneCodeList: this.removeTrim(values.phoneCodeList.split('\n')).toString() })
            .then((res) => {
              const data = res.data.list.map((item) => {
                return {
                  ...item,
                  insAmount: values.insAmount,
                }
              })
              const includes = this.loadData.some((i) => data?.map((j) => j.phoneCode1)?.includes(i.phoneCode1))
              if (!!includes) {
                this.$message.error('存在相同串码')
              } else {
                this.loadData = this.loadData.concat(data)
              }
            })
            .catch((error) => {
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        }
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.submitform.validateFields((err, values) => {
        if (!err) {
          if(this.loadData.length == 0) {
            this.$message.error('没有可保价的商品')
            return false
          }
          const val = {
            ...values,
            orderDate: values?.orderDate,
            accountEntry: values?.accountEntry,
          }
          addInsuredUsingPOST({}, { data: { ...val, insureDetailParams: this.loadData } })
            .then((res) => {
              this.$message.success('操作成功')
              // this.$router.push({ path: `/purchasing/ProtectPriceRecord/index` })
              this.$router.push({ path: `/purchasing/ProtectPriceRecord/${res.data.id}` })
              // 重置表单数据
              this.form.resetFields()
              this.submitform.resetFields()
            })
            .catch((error) => {
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        }
      })
    },
  },
}
</script>
